package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"time"
)

func main() {

	// 创建一个不包含中间件的路由器
	router := gin.New()

	// 全局中间件
	// 使用 Logger 中间件
	router.Use(gin.Logger())

	// 使用 Recovery 中间件
	router.Use(gin.Recovery())

	// 路由添加中间件，可以添加任意多个
	//执行结果
	/**
		Logger1 start
		Logger2 start
		Logger2 end
		Logger1 end
	*/
	router.GET("/ping", Logger1, Logger2)

	// 路由组中添加中间件
	//执行结果
	/**
		LoggerGroup start
		Logger3
		LoggerGroup end
	*/
	authorized := router.Group("/v1")
	authorized.Use(LoggerGroup)//可以添加多个
	{
		authorized.GET("/ping", Logger3)
	}

	//自定义中间件
	router.Use(Logger())
	router.GET("/zdy", LoggerTest)

	router.Run()
}

func LoggerTest(c *gin.Context)  {
	example := c.MustGet("example").(string)

	log.Print(example)
}

func Logger() gin.HandlerFunc {
	
	return func(c *gin.Context) {
		t := time.Now()

		// Set example variable
		c.Set("example", "123456")

		c.Next()

		latency := time.Since(t)
		log.Print(latency)

		// access the status we are sending
		status := c.Writer.Status()
		log.Println(status)
	}
}


func LoggerGroup(c *gin.Context)  {
	fmt.Println("LoggerGroup start")
	c.Next()
	fmt.Println("LoggerGroup end")
}

func Logger3(c *gin.Context) {
	fmt.Println("Logger3")
	c.String(200, "Logger3")
}


func Logger1(c *gin.Context)  {
	fmt.Println("Logger1 start")
	c.Next()
	fmt.Println("Logger1 end")
}

func Logger2(c *gin.Context)  {
	fmt.Println("Logger2 start")
	c.Next()
	fmt.Println("Logger2 end")
}
